<?php
// +----------------------------------------------------------------------
// | ebSIG
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.ebsig.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: liudaojian <liudaojian@ebsig.com>
// +----------------------------------------------------------------------

/**
 * 集点活动定时任务
 * @author   liudaojian <liudaojian@ebsig.com>
 * @version 1.0
 */

namespace App\Http\Controllers\TimedTask\Activity;

use App\Models\Activity\Jd\JdBill;

use App\Models\Activity\Jd\JdCustomer;

use App\Models\Activity\Jd\JdGoods;

use App\Models\Bill\Bill;

use App\Models\Bill\BillGoods;

use App\Models\Mall\MallGroup;

use App\Http\Controllers\Controller;

use Carbon\Carbon;

use Illuminate\Support\Facades\DB;

class JdController extends Controller
{

    /**
     * 获取会员集点数据
     * @return array
     */
    public function getCustomerJd()
    {

        //前一天
//        $yesterday = date('Y-m-d',strtotime("-1 day"));
        $yesterday = date('Y-m-d');

        //查询前一天集点活动
        $jd_data = DB::select("SELECT * FROM jd WHERE '".$yesterday."' BETWEEN DATE_FORMAT(start_time,'%Y-%m-%d') AND DATE_FORMAT(end_time,'%Y-%m-%d')");
        if ( empty( $jd_data ) ) {
            return response()->json(['code' => 10000 , 'message' => '没有集点活动' ]);
        }

        //查询集点活动范围内的订单
        $bill_data = Bill::select('createTime','bill_no','pcustID','custID','mallID')
            ->where('bill_status',4)
            ->whereBetween('timeStamp',[ $yesterday.' 00:00:00',$yesterday.' 23:59:59'])
            ->get()->toArray();


        if ( empty( $bill_data ) ) {
            return response()->json(['code' => 10001 , 'message' => '没有订单' ]);
        }

        //检查订单是否满足集点活动
        $jd_bill = [];
        foreach ( $jd_data as $jd ) {

            foreach ( $bill_data as $bill ) {

                //判断下单时间是否在活动范围内。如果不在则跳过
                if ( $bill['createTime'] < $jd['start_time'] ) {
                    continue;
                }
                if ( $bill['createTime'] > $jd['end_time'] ) {
                    continue;
                }

                $give_jd_num = 0;   //赠送集点数
                $remark = '';       //备注

                /**
                 * 当集点活动指定部分门店时，判断订单门店是否在范围内
                 * store_rule 活动门店类型 1: 全部门店  2：部分门店
                 */
                if ( $jd['store_rule'] == 2  ) {

                    $is_exist_mall = false;

                    if ( $bill['mallID'] ) {
                        if ( !empty( $jd['store_group_id'] ) ) {

                            $store_group_id = json_decode($jd['store_group_id'],true);

                            if ( is_array( $store_group_id ) ) {
                                foreach ( $store_group_id as $item ) {
                                    $mall_group = MallGroup::getCache( $item['id'] );
                                    if ( $mall_group && isset( $mall_group['map'][ $bill['mallID'] ]) ) {
                                        $is_exist_mall = true;
                                        break;
                                    }
                                }
                            }

                        }
                    }

                    if ( !$is_exist_mall ) {
                        $remark = '订单不在活动指定门店内';
                    }

                }

                /**
                 * 判断订单商品是否满足活动条件，如果满足则计算赠送的集点数
                 */
                if ( empty( $remark ) ) {

                    $post_id = [];          //商品数组
                    $total_amount = 0;      //统计订单数量
                    $total_money = 0;       //统计订单金额

                    //获取订单商品
                    $bill_goods = BillGoods::getGoods( $bill['bill_no'] );

                    if ( $bill_goods ) {

                        //活动商品类型 1：全部商品 2：部分商品
                        if ( $jd['goods_rule'] == 1 ) {

                            foreach ( $bill_goods as $item ) {
                                $post_id[] = $item['goods_postID'];
                                $total_amount += $item['goods_amount'];
                                $total_money += $item['goods_purchasePrice']*$item['goods_amount'];
                            }

                        } else if ( $jd['goods_rule'] == 2 ) {

                            //获取集点活动商品
                            $jd_goods = JdGoods::getCache( $jd['activity_id'] );

                            if ( $jd_goods ) {
                                foreach ( $bill_goods as $b_g ) {
                                    //goods_relation 商品关系 1、包含 2、排斥
                                    if ( $jd['goods_relation'] == 1 ) {
                                        if ( in_array( $b_g['goods_postID'] , $jd_goods ) ) {
                                            $post_id[] = $b_g['goods_postID'];
                                            $total_amount += $b_g['goods_amount'];
                                            $total_money += $b_g['goods_purchasePrice']*$b_g['goods_amount'];
                                        }
                                    } else if ( $jd['goods_relation'] == 2 ) {
                                        if ( !in_array( $b_g['goods_postID'] , $jd_goods ) ) {
                                            $post_id[] = $b_g['goods_postID'];
                                            $total_amount += $b_g['goods_amount'];
                                            $total_money += $b_g['goods_purchasePrice']*$b_g['goods_amount'];
                                        }
                                    }

                                }
                            }

                        }

                    }

                    if ( empty( $post_id ) ) {
                        $remark = '没有满足活动的商品';
                    } else {
                        //rule_type 规则类型 1、满元 2、满件
                        if ( $jd['rule_type'] == 1 ) {
                            if ( $total_money >= $jd['rule_amount'] ) {
                                $give_jd_num = floor( $total_money / $jd['rule_amount'] ) * $jd['rule_points'];
                            } else {
                                $remark = '订单商品不满足活动满元的条件';
                            }
                        } else if ( $jd['rule_type'] == 2 ) {
                            if ( $total_amount >= $jd['rule_amount'] ) {
                                $give_jd_num = floor( $total_amount / $jd['rule_amount'] ) * $jd['rule_points'];
                            } else {
                                $remark = '订单商品不满足活动满件的条件';
                            }
                        } else {
                            $remark = '获取集点条件错误';
                        }
                    }

                }

                //保存集点订单
                $jd_bill[] = [
                    'uuid' => makeUuid(),
                    'timeStamp' => Carbon::now(),
                    'creator' => 'system',
                    'createTime' => Carbon::now(),
                    'activity_id' => $jd['activity_id'],
                    'bill_no' => $bill['bill_no'],
                    'pcustID' => $bill['pcustID'],
                    'custID' => $bill['custID'],
                    'dt' => date('Ymd'),
                    'give_jd_num' => $give_jd_num,
                    'remark' => $remark,
                ];


            }

        }

        try {

            //开始事务
            DB::beginTransaction();
           
            //保存集点订单
            foreach ( $jd_bill as $item ) {

                $j_b = JdBill::where([
                    'activity_id'=>$item['activity_id'],
                    'bill_no'=>$item['bill_no'],
                    'pcustID'=>$item['pcustID']
                ])->first();

                if ( !$j_b ) {

                    //给用户赠送集点
                    if ( $item['give_jd_num'] > 0 ) {

                        $jd_customer_obj = JdCustomer::where(['activity_id'=>$item['activity_id'],'pcustID'=>$item['pcustID']])->first();
                        if ( !$jd_customer_obj ) {
                            $jd_customer_obj = new JdCustomer();
                            $jd_customer_obj->uuid = makeUuid();
                            $jd_customer_obj->timeStamp = Carbon::now();
                            $jd_customer_obj->creator = 'system';
                            $jd_customer_obj->createTime = Carbon::now();
                            $jd_customer_obj->activity_id = $item['activity_id'];
                            $jd_customer_obj->pcustID = $item['pcustID'];
                            $jd_customer_obj->custID = $item['custID'];
                            $jd_customer_obj->used_num = 0;

                        }
                        $jd_customer_obj->total_num += $item['give_jd_num'];
                        $jd_customer_obj->not_used_num += $item['give_jd_num'];
                        $jd_customer_obj->save();

                    }

                    unset( $item['custID'] );

                    JdBill::insert( $item );

                }

            }

            //提交事务
            DB::commit();

        } catch ( \Exception $e) {

            //事务回滚
            DB::rollBack();

            return response()->json(['code' => 10002 , 'message' => '定时发放集点出错' ]);

        }

        return response()->json(['code' => 200 , 'message' => 'OK' ]);

    }


}